package com.xxx.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xxx.common.Code;
import com.xxx.common.Result;
import com.xxx.pojo.Address;
import com.xxx.service.AddressService;
import com.xxx.util.ThreadLocalUntil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RestController
@RequestMapping("/address")
public class AddressController {

    @Autowired
    private AddressService service;

    @PostMapping("/save")
    public Result saveAddress(@RequestBody Address address){

        address.setCreateTime(LocalDateTime.now());
        address.setUserId(ThreadLocalUntil.getCurrentId());
        address.setUpdateUser(ThreadLocalUntil.getCurrentId());

        boolean save = service.save(address);
        return save ? new Result(Code.SAVE_OK) : new Result(null, Code.GET_ERR,"系统发生错误，请稍后再试！！！");
    }

    @GetMapping("/defaultAddress")
    public Result getDefaultAddress(){

        Address address = service.getOne(new LambdaQueryWrapper<Address>().eq(Address::getIsDefault, 1));
        return new Result(address,Code.GET_OK);
    }

    /**
     * 获取所有地址
     * @return
     */
    @GetMapping("/getAll")
    public Result getAll(){
        List<Address> addressList = service.list(new LambdaQueryWrapper<Address>().eq(Address::getUserId, ThreadLocalUntil.getCurrentId()));
        return new Result(addressList,Code.GET_OK);
    }

    /**
     * 设置默认
     * @return
     */
    @PutMapping("/setDefault/{id}")
    public Result updateAddress(@PathVariable Long id){

        boolean update = service.update(new LambdaUpdateWrapper<Address>().set(Address::getIsDefault, 0));
        if (update){
            update = service.update(new LambdaUpdateWrapper<Address>().set(Address::getIsDefault,1).eq(Address::getId, id));
        }
        return update ? new Result(Code.UPDATE_OK) : new Result(Code.UPDATE_ERR);
    }

}
